<?php

namespace app\admin\controller\sum\store;

use think\Db;
use app\admin\controller\sum\Common;
use app\admin\model\sum\user\User as UserModel;

class User extends Common
{
    protected $model = null;

    protected $noNeedRight = ['select'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new UserModel;
    }

    /**
     * 员工列表
     */
    public function index()
    {
        $store_id = $this->request->param('store_id');
        if(!$store_id){
            $this->error('参数错误');
        }
        if (!$this->auth->isSuperAdmin()) {
            $admin=$this->auth->getUserInfo();
            if($admin['store_id']!=$store_id){
                $this->error('你不能操作该商户员工');
            }
        }

        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $data = $this->model->sheepFilter()->where('store_id',$store_id)->where('is_staff',1)->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $data);
    }

    public function add()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }
        $params = $this->request->only(['mobile','store_id']);
        if(!$params['mobile']){
            $this->error('参数错误');
        }
        $user=$this->model->where('mobile',$params['mobile'])->find();
        if(!$user){
            $this->error('没有该用户');
        }
        if($user['store_id']>0){
            if($user['store_id']!=$params['store_id']){
                $this->error('该用户已是其他店铺员工');
            }else{
                $this->error('该用户已是员工');
            }
        }
        $user->is_staff=1;
        $user->store_id=$params['store_id'];
        $user->save();
        $this->success('操作成功', null, $user);
    }


    /**
     * 用户详情
     *
     * @param  $id
     */
    public function detail($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $user = $this->model->with(['third_oauth', 'parent_user'])->where('id', $id)->find();
        if (!$user) {
            $this->error(__('No Results were found'));
        }

        $this->success('获取成功', null, $user);
    }


    /**
     * 删除(支持批量)
     *
     * @param  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if (empty($id)) {
            $this->error(__('Parameter %s can not be empty', 'id'));
        }

        $list = $this->model->where('id', 'in', $id)->select();
        $result = Db::transaction(function () use ($list) {
            $count = 0;
            foreach ($list as $item) {
                $item->is_staff=0;
                $item->store_id=0;
                $count += $item->save();
            }

            return $count;
        });

        if ($result) {
            $this->success('操作成功', null, $result);
        } else {
            $this->error(__('没有可执行记录'));
        }
    }

}
